﻿var _this;
// var canScroll = false;
var canShowMoreJson = ['#nav_new', '#nav_hot', '#nav_group', '#nav_list'];

// 瀑布流参数
var options = {
    autoResize : true,
    container : {},
    offset : 5,
    itemWidth : 98
};

// 最新
var _new = {
    rec : 'newrec.html',
    rec_pno : 0,
    rec_psize : 12,
    pageCount : 0,
    result : null,
    item_index : 0,
    index : 0,
    item_more : false,
    allJsonNew : null,
    hasMoreNew : true,
    more : true
};

// 最热
var _hot = {
    rec : 'hotrec.html',
    rec_pno : 0,
    rec_psize : 12,
    pageCount : 0,
    result : null,
    item_index : 0,
    index : 0,
    item_more : false,
    allJsonHot : null,
    hasMoreHot : true,
    more : true
};

// 组图
var _group = {
    rec : 'searec.html',
    rec_pno : 0,
    rec_psize : 12,
    pageCount : 0,
    result : null,
    item_index : 0,
    index : 0,
    item_more : false,
    allJsonGroup : null,
    hasMoreGroup : true,
    more : true
};

// 榜单
var _list = {
    rec : 'boarddata.html',
    rec_pno : 0,
    rec_psize : 99,
    pageCount : 0,
    result : null,
    item_index : 0,
    index : 0,
    item_more : false,
    allJsonList : null,
    more : true
};

// 移除等待图标并且显示加载好的图片
function removeWaitIcon(_this) {
    $(_this).css("visibility", "visible");
    $(_this).parent().removeClass("wait_blue");
}

// 组图事件函数
function openNewGroupPicPage(id) {
    statistictGroupHumbnail();
    setTimeout(function() {
        window.location.href = "groupdetail.html?id=" + id + "#id=" + id + "&pno=0";
    }, 300);
}

// 榜单事件函数
function change2BoardPage(id) {
    statistictListCatagory();
    setTimeout(function() {
        window.location.href = "board.html?id=" + id;
    }, 300);
}

// 最新和最热事件函数
function goNewPicDetailPage(pno, route) {
    setTimeout(function() {
        window.location.href = "photodetail.html?route=" + route + "&gid=" + pno + "#pno=" + pno;
    }, 300);
}

// gif图片显示时间
// var gifShowTime = 0;
// var isHide = false;
// var gifShowInter = setInterval(function() {
// gifShowTime++;
// if (gifShowTime == 5) {
// var gifHtml = '<div id="gifLayer" onclick="isHide=true;"><img src="apache/images/2.gif" /></div>';
// $('html,body').addClass('hidden');
// $('body').append(gifHtml);
// }
// if (isHide || (gifShowTime == 15)) {
// $('#gifLayer').remove();
// $('html,body').removeClass('hidden');
// clearInterval(gifShowInter);
// }
// }, 1000);
$(function() {
    // 导航栏
    var $nav_new = $('#nav_new');
    var $nav_hot = $('#nav_hot');
    var $nav_group = $('#nav_group');
    var $nav_list = $('#nav_list');

    // 内容版块
    var $new_tiles = $("#new_tiles");
    var $hot_tiles = $("#hot_tiles");
    var $group_tiles = $("#group_tiles");
    var $list_tiles = $("#list_tiles");

    // 图片板块
    // var $new_tiles_li = $('#new_tiles li');
    // var $hot_tiles_li = $('#hot_tiles li');
    // var $group_tiles_li = $('#group_tiles li');
    // var $list_tiles_li = $('#list_tiles li');
    // 页面初始化，加载最新栏数据
    // getNewImgData(_new.rec_pno, _new.rec_psize, _new.rec, 1);
    if (window.location.hash) {
        switch(window.location.hash.substr(1).split('=')[1]) {
            case '1':
                addNavEventListen(1);
                break;
            case'2':
                addNavEventListen(2);
                break;
            case '3':
                addNavEventListen(3);
                break;
            case '4':
                addNavEventListen(4);
        }
    } else {
        getNewImgData(_new.rec_pno, _new.rec_psize, _new.rec, 1);
    }

    // 跳转到查找页
    $("#goSearchPage").click(function() {
        statisticSearchButton();
        setTimeout(function() {
            window.location.href = "search.html";
        }, 500)
    });
    // 跳转到易查首页
    $("#back2mobi").click(function() {
        statisticYichaHome();
        setTimeout(function() {
            window.location.href = "http://yicha.mobi/";
        }, 500)
    });
    // 导航栏事件
    $('#home_nav .dh-div').bind('click', function() {
        statisticNavNew();
        _this = this;
        if (!$(_this).hasClass('dh-1')) {
            var href = window.location.href.split('#')[0];
            var tag = $(_this).index() + 1;
            switch(tag) {
                case 1:
                    window.location.href = href + '#tag=1';
                    break;
                case 2:
                    window.location.href = href + '#tag=2';
                    break;
                case 3:
                    window.location.href = href + '#tag=3';
                    break;
                case 4:
                    window.location.href = href + '#tag=4';
                    break;
            }
            addNavEventListen(tag);
        }
    });

    // 导航栏事件监听
    function addNavEventListen(tag) {
        $('.dh-1').removeClass('dh-1').attr('stop', 'true');
        $('#pagecontent .current').removeClass('current');
        switch (tag) {
            case 1:
                statisticNavNew();
                $nav_new.addClass('dh-1').removeAttr('stop');
                $new_tiles.addClass('current');
                change2NewPage();
                break;
            case 2:
                statisticNavHot();
                $nav_hot.addClass('dh-1').removeAttr('stop');
                $hot_tiles.addClass('current');
                change2HotPage();
                break;
            case 3:
                statisticNavGroup();
                $nav_group.addClass('dh-1').removeAttr('stop');
                $group_tiles.addClass('current');
                change2GroupPage();
                break;
            case 4:
                statisticNavList();
                $nav_list.addClass('dh-1').removeAttr('stop');
                $list_tiles.addClass('current');
                change2ListPage();
        }
    }

    // 屏幕滚动加载更多
    var chooseTimer = null;
    $(window).scroll(function() {
        if (chooseTimer) {
            clearTimeout(chooseDivHasClass);
            chooseTimer = setTimeout(chooseDivHasClass, 1000);
        } else {
            chooseTimer = setTimeout(chooseDivHasClass, 1000);
        }
    });
    // $(document).live("touchmove", function() {
    // if (chooseTimer) {
    // clearTimeout(chooseDivHasClass);
    // chooseTimer = setTimeout(chooseDivHasClass, 300);
    // } else {
    // chooseTimer = setTimeout(chooseDivHasClass, 300);
    // }
    // });
    // 切换到最新栏目
    function change2NewPage() {
        if (!_new.allJsonNew) {
            getNewImgData(_new.rec_pno, _new.rec_psize, _new.rec, 1);
        } else if (_new.more) {
            _new.item_more ? preLoadImagemore(1) : preLoadImage(1);
        } else {
            // canScroll = true;
        }
    }

    // 切换到最热栏目
    function change2HotPage() {
        if (!_hot.allJsonHot) {
            getNewImgData(_hot.rec_pno, _hot.rec_psize, _hot.rec, 2);
        } else if (_hot.more) {
            _hot.item_more ? preLoadImagemore(2) : preLoadImage(2);
        } else {
            // canScroll = true;
        }
    }

    // 切换到组图栏目
    function change2GroupPage() {
        if (!_group.allJsonGroup) {
            getNewImgData(_group.rec_pno, _group.rec_psize, _group.rec, 3);
        } else if (_group.more) {
            _group.item_more ? preLoadImagemore(3) : preLoadImage(3);
        } else {
            // canScroll = true;
        }
    }

    // 切换到榜单栏目
    function change2ListPage() {
        if (!_list.allJsonList) {
            getNewImgData(_list.rec_pno, _list.rec_psize, _list.rec, 4);
        } else if (_list.more) {
            preLoadImage(4);
        } else {
            // canScroll = true;
        }
    }

    // 动态修改等待图标的位置
    function changePosition() {
        var top = typeof window.pageYOffset != "undefined" ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
        var pHeight = window.innerHeight != null ? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null;
        var Centertop = top + pHeight - 56;
        document.getElementById("nav_loading").style.position = "absolute";
        document.getElementById("nav_loading").style.top = Centertop + "px";
    }

    // 隐藏等待图标
    function nav_hideLoaing() {
        $('#nav_loading').hide();
    }

    // 显示等待图标
    function nav_showLoaing() {
        $('#nav_loading').show();
    }

    // 屏幕滚动回调函数
    function chooseDivHasClass() {
        if (window.scrollY + window.innerHeight >= (parseInt(document.body.scrollHeight - 50))) {
            // if (canScroll) {            $.each(canShowMoreJson, function(n, value) {
                if ($(value).hasClass('dh-1')) {
                    var tag = n + 1;
                    switch (tag) {
                        case 1:
                            // canScroll = false;
                            if (_new.hasMoreNew) {
                                getMoreGoodsInShops(tag);
                            }
                            break;
                        case 2:
                            // canScroll = false;
                            if (_hot.hasMoreHot) {
                                getMoreGoodsInShops(tag);
                            }
                            break;
                        case 3:
                            // canScroll = false;
                            if (_group.hasMoreGroup) {
                                getMoreGoodsInShops(tag);
                            }
                    }
                }
            });
            // }        }
    }

    // ajax初次请求数据
    function getNewImgData(pno, psize, curl, tag) {
        $("#default-loading").hide();
        nav_showLoaing();
        $.ajax({
            type : 'POST',
            url : curl,
            data : "pno=" + pno + "&psize=" + psize,
            dataType : "json",
            success : function(result) {
                switch (tag) {
                    case 1:
                        _new.result = result;
                        break;
                    case 2:
                        _hot.result = result;
                        break;
                    case 3:
                        _group.result = result;
                        break;
                    case 4:
                        _list.result = result;
                }
                preLoadImage(tag);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常，请重试！");
            }
        });
    }

    // ajax请求更多数据
    function getMoreGoodsInShops(tag) {
        changePosition();
        nav_showLoaing();
        if (tag == 1) {
            _new.rec_pno++;
            statisticNewNum(_new.rec_pno);
            $.ajax({
                type : 'POST',
                url : _new.rec,
                data : "pno=" + _new.rec_pno + "&psize=" + _new.rec_psize,
                dataType : "json",
                success : function(result) {
                    if (_new.rec_pno < _new.pageCount) {
                        _new.result = result;
                        preLoadImagemore(tag);
                        _new.hasMoreNew = true;
                    } else {
                        _new.hasMoreNew = false;
                    }
                }
            });
        }
        if (tag == 2) {
            _hot.rec_pno++;
            statisticHotNum(_hot.rec_pno);
            $.ajax({
                type : 'POST',
                url : _hot.rec,
                data : "pno=" + _hot.rec_pno + "&psize=" + _hot.rec_psize,
                dataType : "json",
                success : function(result) {
                    if (_hot.rec_pno < _hot.pageCount) {
                        _hot.result = result;
                        console.log(_hot.index);
                        preLoadImagemore(tag);
                        _hot.hasMoreHot = true;
                    } else {
                        _hot.hasMoreHot = false;
                    }
                }
            });
        }
        if (tag == 3) {
            _group.rec_pno++;
            statisticGroupNum(_group.rec_pno);
            $.ajax({
                type : 'POST',
                url : _group.rec,
                data : "pno=" + _group.rec_pno + "&psize=" + _group.rec_psize,
                dataType : "json",
                success : function(result) {
                    if (_group.rec_pno < _group.pageCount) {
                        _group.result = result;
                        preLoadImagemore(tag);
                        _group.hasMoreGroup = true;
                    } else {
                        _group.hasMoreGroup = false;
                    }
                }
            });
        }
    }

    // 加载更多数据
    function preLoadImagemore(tag) {
        var item;
        switch (tag) {
            case 1:
                if (!$nav_new.attr("stop")) {
                    _new.item_more = true;
                    item = _new.result.map.showImageList[_new.item_index];
                    preImgReadyMore(item, tag);
                }
                break;
            case 2:
                if (!$nav_hot.attr("stop")) {
                    _hot.item_more = true;
                    item = _hot.result.map.showImageList[_hot.item_index];
                    preImgReadyMore(item, tag);
                }
                break;
            case 3:
                if (!$nav_group.attr("stop")) {
                    _group.item_more = true;
                    item = _group.result.map.showImageList[_group.item_index];
                    preImgReadyMore(item, tag);
                }
        }
    }

    // 加载更多数据的图片预处理(最新、最热、组图)
    function preImgReadyMore(item, tag) {
        imgReady(item.simageUrls, function() {
            item.simageUrls = item.simageUrls + "$$" + this.width + "$$" + this.height;
            onLoadData(item, tag);
            nav_hideLoaing();
        });
    }

    // 加载数据到栏目
    function onLoadData(item, tag) {
        var html = a = '';
        if (tag == 4) {
            a = item.img.split("$$");
        } else {
            a = item.simageUrls.split("$$");
        }
        var originalWidth = a[1];
        var originalHeight = a[2];
        var picScale = originalWidth / originalHeight;
        var Dheight = 90 / picScale;
        if (tag == 4) {
            html += '<li id="' + _list.index + '" class="wait_blue" onclick="change2BoardPage(' + item.id + ')">';
            html += '<img src="' + a[0] + '" width="90" height="' + Dheight + '" onload="removeWaitIcon(this)">';
            html += '<div class="list-foot footerlist">' + item.name + '</div></li>';
            $('#list_tiles').append(html);
        } else {
            switch (tag) {
                case 1:
                    html += '<li id="' + _new.index + '"  class="' + item.groupId + ' wait_blue" onclick="goNewPicDetailPage(\'' + _new.index + '\',\'' + item.bigId + '\')">';
                    html += '<img src="' + a[0] + '" width="90" height="' + Dheight + '" onload="removeWaitIcon(this)">';
                    html += '</li>';
                    $new_tiles.append(html);
                    break;
                case 2:
                    html += '<li id="' + _hot.index + '"  class="' + item.groupId + ' wait_blue" onclick="goNewPicDetailPage(\'' + _hot.index + '\',\'' + item.bigId + '\')">';
                    html += '<img src="' + a[0] + '" width="90" height="' + Dheight + '" onload="removeWaitIcon(this)">';
                    html += '</li>';
                    $hot_tiles.append(html);
                    break;
                case 3:
                    html += '<li id="' + _group.index + '"  class="' + item.groupId + ' wait_blue" onclick="openNewGroupPicPage(\'' + item.groupId + '\')">';
                    html += '<img src="' + a[0] + '" width="90" height="' + Dheight + '" onload="removeWaitIcon(this)">';
                    if (parseInt(item.groupNum) > 9) {
                        html += '<div class="list-foot footergroupqt">' + item.groupNum + '</div></li>';
                    } else {
                        html += '<div class="list-foot footergroup">' + item.groupNum + '</div></li>';
                    }
                    $group_tiles.append(html);
            }
        }
        applyLayout(tag);
    }

    ;

    // 瀑布流布局
    function applyLayout(tag) {
        nav_hideLoaing();
        var handler = null;
        if (handler)
            handler.wookmarkClear();
        switch (tag) {
            case 1:
                handler = $('#new_tiles li');
                options.container = $new_tiles;
                handler.wookmark(options);
                break;
            case 2:
                handler = $('#hot_tiles li');
                options.container = $hot_tiles;
                handler.wookmark(options);
                break;
            case 3:
                handler = $('#group_tiles li');
                options.container = $group_tiles;
                handler.wookmark(options);
                break;
            case 4:
                handler = $('#list_tiles li');
                options.container = $list_tiles;
                handler.wookmark(options);
        }
        switch (tag) {
            case 1:
                _new.index++;
                console.log(_new.item_index);                // console.log(_new.index);
                if (_new.item_index < _new.result.map.showImageList.length - 1) {
                    _new.item_index++;
                    _new.more = true;
                    _new.item_more ? preLoadImagemore(tag) : preLoadImage(tag);
                } else {
                    _new.more = false;
                    // canScroll = true;
                    _new.item_index = 0;
                }
                break;
            case 2:
                _hot.index++;
                if (_hot.item_index < _hot.result.map.showImageList.length - 1) {
                    _hot.item_index++;
                    _hot.more = true;
                    _hot.item_more ? preLoadImagemore(tag) : preLoadImage(tag);
                } else {
                    _hot.more = false;
                    // canScroll = true;                    _hot.item_index = 0;
                }
                break;
            case 3:
                _group.index++;
                if (_group.item_index < _group.result.map.showImageList.length - 1) {
                    _group.item_index++;
                    _group.more = true;
                    _group.item_more ? preLoadImagemore(tag) : preLoadImage(tag);
                } else {
                    _group.more = false;
                    // canScroll = true;
                    _group.item_index = 0;
                }
                break;
            case 4:
                _list.index++;
                if (_list.item_index < _list.result.map.showImageList.length - 1) {
                    _list.item_index++;
                    _list.more = true;
                    preLoadImage(tag);
                } else {
                    _list.more = false;                    _list.item_index = 0;
                }
        }
    }

    ;

    // 初次数据加载
    function preLoadImage(tag) {
        var item;
        if (tag == 4) {
            if (!$nav_list.attr("stop")) {
                item = _list.result.map.showImageList[_list.item_index];
                preListImgReady(item, tag);
            }
        } else {
            switch (tag) {
                case 1:
                    if (!$nav_new.attr("stop")) {
                        item = _new.result.map.showImageList[_new.item_index];
                        preImgReady(item, tag);
                    }
                    break;
                case 2:
                    if (!$nav_hot.attr("stop")) {
                        item = _hot.result.map.showImageList[_hot.item_index];
                        preImgReady(item, tag);
                    }
                    break;
                case 3:
                    if (!$nav_group.attr("stop")) {
                        item = _group.result.map.showImageList[_group.item_index];
                        preImgReady(item, tag);
                    }
            }
        }
    }

    // 初次数据加载的图片预处理(最新、最热、组图)
    function preImgReady(item, tag) {
        imgReady(item.simageUrls, function() {
            item.simageUrls = item.simageUrls + "$$" + this.width + "$$" + this.height;
            selectResultWithTag(item, tag);
        });
    }

    // 初次数据加载的图片预处理(榜单)
    function preListImgReady(item, tag) {
        imgReady(item.img, function() {
            item.img = item.img + "$$" + this.width + "$$" + this.height;
            selectResultWithTag(item, tag);
        });
    }

    // 获取图片的宽度和高度
    function imgReady(src, ready) {
        var img = document.createElement('img');
        img.src = src;
        img.onload = function() {
            ready.call(img);
        };
    }

    // 初次加载数据
    function selectResultWithTag(item, tag) {
        nav_showLoaing();
        switch (tag) {
            case 1:
                if (!_new.allJsonNew) {
                    _new.allJsonNew = _new.result.map.showImageList;
                    _new.pageCount = _new.result.map.pageCount;
                }
                break;
            case 2:
                if (!_hot.allJsonHot) {
                    _hot.allJsonHot = _hot.result.map.showImageList;
                    _hot.pageCount = _hot.result.map.pageCount;
                }
                break;
            case 3:
                if (!_group.allJsonGroup) {
                    _group.allJsonGroup = _group.result.map.showImageList;
                    _group.pageCount = _group.result.map.pageCount;
                }
                break;
            case 4:
                if (!_list.allJsonList) {
                    _list.allJsonList = _list.result.map.showImageList;
                    _list.pageCount = _list.result.map.pageCount;
                }
        }
        onLoadData(item, tag);
    }

});

// 统计函数
function statisticYichaHome() {
    var para = "idx.do?pvt=index";
    requestStatistic("首页", para);
}

function statisticNavNew() {
    var para = "idx.do?pvt=new";
    requestStatistic("切换最新瀑布流", para);
}

function statisticNavHot() {
    var para = "idx.do?pvt=hot";
    requestStatistic("切换最热瀑布流", para);
}

function statisticNavGroup() {
    var para = "idx.do?pvt=sea";
    requestStatistic("切换组图瀑布流", para);
}

function statisticNavList() {
    var para = "idx.do?pvt=board";
    requestStatistic("切换榜单瀑布流", para);
}

function statisticSearchButton() {
    var para = "search.do";
    requestStatistic("进搜索页", para);
}

function statistictGroupHumbnail() {
    var para = "seafirst.do?gid=10";
    requestStatistic("瀑布流进浏览", para);
}

function statistictListCatagory() {
    var para = "board.do?id=1";
    requestStatistic("进榜单页", para);
}
